package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import  bean.ActionForm;
import  bean.Form;
import  bean.XMLBean;
import  constant.Constant;
import  util.StringUtils;


public class ActionServlet extends HttpServlet {
	
	public static Logger logger = Logger.getLogger("ActionServlet");

	public ActionServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String path = StringUtils.getPath(request.getServletPath());
		Map<String, XMLBean> map = (Map<String, XMLBean>) this.getServletContext().getAttribute("struts");
		XMLBean bean = map.get(path);
		if(null != bean){
			String beanClass = bean.getBeanClass();
			ActionForm actionForm = Form.full(beanClass, request);
			String actionType = bean.getActionType();
			Action action = null;
			Class<?> clazz = null;
			try {
				clazz = Class.forName(actionType);
				action = (Action) clazz.newInstance();
				String url = action.execute(request, response, actionForm, bean.getForwards());
				RequestDispatcher dis = request.getRequestDispatcher(url);
				dis.forward(request, response);
				
			} catch (Exception e) {
				logger.info(Constant.EXCEPTIONMSG+e);
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

	public void init() throws ServletException {
		
	}

}
